use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::common::Response;

#[derive(Clone, Debug, Serialize)]
pub struct ApiQuotaReq {
    cgi_path: String,
}

impl ApiQuotaReq {
    pub fn new<T>(path: T) -> Self
    where
        T: AsRef<str>,
    {
        Self {
            cgi_path: path.as_ref().to_owned(),
        }
    }
}
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct Quota {
    pub daily_limit: u32,
    pub used: u32,
    pub remain: u32,
}

#[derive(Clone, Copy, Debug, Deserialize)]
pub struct RateLimit {
    pub call_count: u32,
    pub refresh_second: u32,
}

#[derive(Clone, Copy, Debug, Deserialize)]
pub struct ComponentRateLimit {
    pub call_count: u32,
    pub refresh_second: u32,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ApiQuotaRes {
    pub quota: Quota,
    pub rate_limit: Option<RateLimit>,
    pub cmponent_rate_limit: Option<ComponentRateLimit>,
}

pub async fn get_api_quota<T>(
    token: T,
    quota: &ApiQuotaReq,
) -> Result<Response<ApiQuotaRes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = format!(
        "https://api.weixin.qq.com/cgi-bin/openapi/quota/get?access_token={}",
        token.as_ref()
    );
    let client = Client::new();
    client
        .post(url)
        .json(quota)
        .send()
        .await?
        .json::<Response<ApiQuotaRes>>()
        .await
}
